package org.misty.seckill.service.impl;

import org.misty.seckill.dao.OrderDao;
import org.misty.seckill.model.Order;
import org.misty.seckill.model.SOrder;
import org.misty.seckill.model.User;
import org.misty.seckill.service.OrderService;
import org.misty.seckill.util.SnowflakeIdWorker;
import org.misty.seckill.vo.SGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {
  @Autowired
  private OrderDao orderDao;
  @Autowired
  private SnowflakeIdWorker snowflake;

  @Deprecated
  @Override
  public SOrder findByUserAndGoods(long userId, long goodsId) {
    return orderDao.findByUserAndGoods(userId, goodsId);
  }

  @Override
  @Transactional
  public Order createOrder(User user, SGoodsVo SGoodsVo) {
    var order = new Order();
    order.setId(snowflake.nextId());
    order.setCreateDate(new Date());
    order.setAddrId(0);
    order.setCount(1);
    order.setGoodsId(SGoodsVo.getId());
    order.setName(SGoodsVo.getName());
    order.setPrice(SGoodsVo.getPriceSpike());
    order.setChannel(1);
    order.setStatus(0);
    order.setUserId(user.getId());
    orderDao.insertOrder(order);

    var sOrder = new SOrder();
    sOrder.setId(snowflake.nextId());
    sOrder.setSeckillId(SGoodsVo.getSid());
    sOrder.setOrderId(order.getId());
    sOrder.setUserId(user.getId());
    orderDao.insertSOrder(sOrder);

    return order;
  }

  @Override
  public Order findByUserAndId(long userId, long orderId) {
    return orderDao.findByUserAndId(userId, orderId);
  }

  @Transactional
  @Override
  public void clearAll() {
    orderDao.clearOrders();
    orderDao.clearSOrders();
  }
}
